package me.pinion;

import com.jfinal.config.*;
import com.jfinal.ext.interceptor.SessionInViewInterceptor;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.druid.DruidPlugin;
import com.jfinal.render.ViewType;
import me.pinion.controller.route.AutoRoutes;
import me.pinion.exception.BookExistException;
import me.pinion.handler.AccountHandler;
import me.pinion.interceptor.RequestCheckInterceptor;
import me.pinion.plugin.AutoActiveRecordPlugin;
import me.pinion.service.BookService;
import java.io.*;

public class XTimeConfig extends JFinalConfig {


    public static OSName OS_NAME;
    private static String DB_HOST = "115.29.39.22";
    private static String DB_PORT = "3306";
    private static String DB = "tagxtime_dev";
    private static String DB_USERNAME = "root";
    private static String DB_PASSWORD = "taotao_qiu";

    @Override
    public void configConstant(Constants me) {
        me.setDevMode(true);
        me.setViewType(ViewType.FREE_MARKER);
        me.setError403View("/error/403.html");
    }

    @Override
    public void configRoute(Routes me) {
        me.add(new AutoRoutes());
    }

    @Override
    public void configPlugin(Plugins me) {
        DruidPlugin dp = new DruidPlugin("jdbc:mysql://${DB_HOST}:${DB_PORT}/${DB}?characterEncoding=utf8", DB_USERNAME, DB_PASSWORD);
        me.add(dp);
        ActiveRecordPlugin arp = new AutoActiveRecordPlugin(dp);
        me.add(arp);
    }

    @Override
    public void configInterceptor(Interceptors me) {
        me.add(new RequestCheckInterceptor());
        me.add(new SessionInViewInterceptor());
    }

    @Override
    public void configHandler(Handlers me) {
        me.add(new AccountHandler());
    }

    @Override
    public void afterJFinalStart() {
        String os = System.getProperty("os.name");
        Log.i(os);
        if ("Mac OS X".equals(os)) {
            this.OS_NAME = OSName.MAC_OS_X;
        } else {
            this.OS_NAME = OSName.LINUX;
        }
        Log.i(new GroovyTest().sayHello());
    }

    public static void loadLocalBook() throws IOException {
        Map<String, StringBuffer> map = new HashMap<String, StringBuffer>();
        File dir = new File("/Volumes/MAC/Download/小说/load");

        File[] files = dir.listFiles();
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            handleFile(file);
        }
    }

    public static void handleFile(final File file) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    BookService.getInstance().loadFile(file);
                } catch (BookExistException e) {
                    throw new RuntimeException();
                }
            }
        }).start();
    }

    public enum OSName {
        LINUX, WINDOWS, MAC_OS_X
    }
}
